<template>
  <CommonCard title="今日订单" :value="numberFormat(orderToday)">
    <div ref="lineChartRef" style="width: 100%; height: 100%"></div>
    <template #footer>
      <span>昨日订单量</span>
      <span class="emphasis">{{ moneyFormat(orderLastDay) }}</span>
    </template>
  </CommonCard>
</template>

<script lang="ts">
import CommonCard from "./CommonCard.vue"
export default {
  name: "TodayOrders",
  components: { CommonCard },
}
</script>
<script lang="ts" setup>
import * as echarts from "echarts"
import type { EChartsType } from "echarts"
import { ref, onMounted, computed, watch } from "vue"
import { useReportDataStore } from "@/stores/reportData"
import { formatData } from "@/hooks/useFormat"
const reportDataStore = useReportDataStore()
const { numberFormat, moneyFormat } = formatData()

const orderToday = computed(() => reportDataStore.reportData.orderToday)
const orderLastDay = computed(() => reportDataStore.reportData.orderLastDay)
const orderTrend = computed(() => reportDataStore.reportData.orderTrend)
const orderTrendAxis = computed(() => reportDataStore.reportData.orderTrendAxis)

const lineChartRef = ref(null)

let myChart: EChartsType

// 让代码在读取时不要执行，因为还没有拿到dome元素
// 所以包装成函数返回值的形式，在页面挂载完成时调用，获取数据
const getOption = () => {
  return {
    xAxis: {
      boundaryGap: false, // 两侧不留空白
      data: orderTrendAxis.value, // x轴数据列表
      show: false,
    },
    yAxis: {
      show: false,
    },
    series: [
      {
        name: "实时订单数",
        type: "line",
        data: orderTrend.value,
        // 曲线平滑
        smooth: true,
        // 设置区域样式 来代替折线
        areaStyle: { color: "#93b5cf" },
        // 折线点的样式
        itemStyle: {
          opacity: 0,
        },
        // 线的样式
        lineStyle: {
          opacity: 0,
        },
      },
    ],
    grid: {
      left: 0,
      top: 0,
      right: 0,
      bottom: 0,
    },
    tooltip: {
      trigger: "axis",
      confine: true,
    },
  }
}

// 1. 当页面组件挂载完毕的时候 才要使用数据生成对应的图形
onMounted(() => {
  myChart = echarts.init(lineChartRef.value)

  // 当浏览器宽度发生变化的时候，图表也要发生变化
  window.addEventListener("resize", () => {
    myChart && myChart.resize()
  })
})

// 2.监视Store数据，当数据更新时，立刻渲染页面
watch(orderToday, () => myChart.setOption(getOption()))
</script>

<style lang="scss" scoped></style>
